package ip

import (
	"bytes"
	"strconv"
	"strings"
)

// StringIpToInt 把ip字符串转成int64
func StringIpToInt(ip string) int64 {
	ipParts := strings.Split(ip, ".")
	var ipInt int64
	var pos uint = 24
	for _, ipPort := range ipParts {
		tempInt, _ := strconv.ParseInt(ipPort, 10, 64)
		tempInt = tempInt << int64(pos)
		ipInt = ipInt | tempInt
		pos -= 8
	}
	return ipInt
}

// IntIpToString 把ip从int64转成string
func IntIpToString(ipInt int64) string {
	ipSegs := make([]string, 4)
	length := len(ipSegs)
	buffer := bytes.NewBufferString("")
	for i := 0; i < length; i++ {
		tempInt := ipInt & 0xFF
		ipSegs[length-i-1] = strconv.FormatInt(tempInt, 10)
		ipInt = ipInt >> 8
	}
	for i := 0; i < length; i++ {
		buffer.WriteString(ipSegs[i])
		if i < length-1 {
			buffer.WriteString(".")
		}
	}
	return buffer.String()
}
